//
//  HMComposeView.swift
//  MyWeibo
//
//  Created by apple on 16/4/25.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import pop

class HMComposeView: UIView {
    
    //懒加载按钮数组 空数组
    lazy var menuButtons:[HMComposeMenuButton] = []
    
    //懒加载按钮模型数据组
    lazy var array:[HMComposeMenuItemInfo] = {
        
        return self.itemInfos()
    }()
    
    //当前视图添加到的控制器
    var target : UIViewController?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //设置UI
    func setupUI(){
        
        //设置大小
        frame = UIScreen.mainScreen().bounds
        //添加背景颜色
        backgroundColor = UIColor.cyanColor()
        
        //添加磨砂背景
        let image = UIImage.getScreenShot().applyLightEffect()
        
        let imageView = UIImageView(image: image)
        
        //添加到父view上
        addSubview(imageView)
        
        //天机标语
        addSubview(sloganImage)
        
        //设置标语的约束
        sloganImage.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(self)
            
            make.top.equalTo(100)
        }
        
        //添加菜单
        addMenuButtons()
        
    }
    
    //添加菜单按钮
    private func addMenuButtons(){
        
        //计算每一个按钮之间的间距
        let itemW : CGFloat = 80
        let itemH: CGFloat = 110
        
        let margin = (SCREENW - 3 * itemW) / 4
        
        //循环创建button
        for (i,value) in array.enumerate(){
            
            
            //创建一个button
            let button = HMComposeMenuButton(textColor: UIColor.darkGrayColor(), fontSize: 14)
            
            //添加点击事件
            button.addTarget(self, action: "menuButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            //记录tag
            button.tag = i
            //设置文字
            button.setTitle(value.title, forState: UIControlState.Normal)
            //设置背景图片
            button.setImage(UIImage(named: value.icon!), forState: UIControlState.Normal)
            //设置按钮的大小
            button.frame.size = CGSize(width: itemW, height: itemH)
            //添加到view上
            addSubview(button)
            //添加到数组中
            menuButtons.append(button)
            
            
            //计算按钮呢的位置
            let col = i % 3
            let row = i / 3
            
            //计算x的值
            button.frame.origin.x = CGFloat(col) * itemW + CGFloat(col + 1) * margin
            //计算y的值
            button.frame.origin.y = CGFloat(row) * itemH + CGFloat(row) * 10 + SCREENH
            
        }
        
    }
    
    
    
    //读取按钮数据  返回按钮数据数组
    private func itemInfos()->[HMComposeMenuItemInfo]{
        
        //读取plist文件地址
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        //从地址读出数据
        let array = NSArray(contentsOfFile: path)!
        
        
        //创建一个数组来保存数据
        var tempArray : [HMComposeMenuItemInfo] = []
        
        //遍历数组字典转模型
        for value in array {
            
            let info = HMComposeMenuItemInfo(dict: value as! [String:AnyObject])
            
            tempArray.append(info)
            
        }
        return tempArray
        
    }
    //提供给外界一个方法来获取主控制器
    func show(target:UIViewController?){
        
        //添加view到传进来的controller上
        target?.view.addSubview(self)
        
        //用来记录传进来的控制器
        self.target = target
        
    }
    
    
    //动画弹出
    override func didMoveToSuperview(){
        
        super.didMoveToSuperview()
        //遍历执行动画
        for (index,value) in menuButtons.enumerate(){
            
            //调用执行动画方法
            animation(value, index: index, isUP: true)
            
        }
    }
    //点击动画消失
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        //调用父类
        super.touchesBegan(touches, withEvent: event)
        
        //执行动画
        for (index,value) in menuButtons.reverse().enumerate(){
            animation(value, index: index, isUP: false)
            
        }
         
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            
            self.removeFromSuperview()
            
        }
        
    }
    
    
    //创建一个动画方法
    private func animation(value:UIView,index:Int,isUP:Bool){
        
        //初始化动画对象
        let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        
        //指定动画要要执行的结束位置
        anim.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y + ( isUP ? -350 : 350 )))
        
        //设置动画的属性
        //设置弹性速度
        anim.springSpeed = 10
        //设置弹性弧度
        anim.springBounciness = 8
        
        //两种方法弹出button  一种gcd挨个弹出
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(index) * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
//            
//            //添加动画
//            value.pop_addAnimation(anim, forKey: nil) }
        //第二种方法用框架
        anim.beginTime = Double(index) * 0.025 + CACurrentMediaTime()
        
        //添加动画
        value.pop_addAnimation(anim, forKey: nil)
        
    }
    
    //点击事件的响应
   @objc private func menuButtonClick(button:UIButton){
        
        //添加动画
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            
            //遍历判断来调整button的大小
            
            for value in self.menuButtons {
                
                value.alpha = 0.01
                
                //如果数组里面的button和传进来的button相同就改变大小
                if value == button {
                    
                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else{
                    
                    value.transform = CGAffineTransformMakeScale(0.01, 0.01)
                }
            }
            }) { (_) -> Void in
                
                //执行完跳转动画之后弹出控制器
                
                //取出模型中的tag
                let model = self.array[button.tag]
                //通过类名加载控制器
                let type = NSClassFromString(model.className!)! as! UIViewController.Type
                
                let vc = type.init()
                
             
                //view是不能推出控制器的 只能通过控制器推出
                self.target?.presentViewController(UINavigationController(rootViewController: vc), animated: true, completion: { () -> Void in
                    //推出控制器之后再把compose移除
                    self.removeFromSuperview()
                })
        }
    }
    
    
    //懒加载标语
    private lazy var sloganImage = UIImageView(image: UIImage(named: "compose_slogan"))
    
}
